import { Injectable, Injector } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import * as signalR from '@microsoft/signalr';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { environment } from '../../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class SignalrService {
  private hubConnection: signalR.HubConnection;
  public isConnected = new BehaviorSubject<boolean>(false);
  public dashboardData = new BehaviorSubject<any>(null);
  private lastMockDataTime: Date | null = null;

  constructor(
    private injector: Injector
  ) { }

  /**
   * 初始化连接
   */
  public initConnection(): void {
    const baseUrl = environment.apis.default.url;
    
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(`${baseUrl}/dashboardHub`)
      .withAutomaticReconnect([0, 2000, 5000, 10000, 30000])
      .configureLogging(signalR.LogLevel.Information)
      .build();

    this.startConnection();
    
    console.log(`正在连接到SignalR Hub: ${baseUrl}/dashboardHub`);
  }

  /**
   * 开始连接
   */
  private startConnection(): void {
    setTimeout(() => {
      if (!this.isConnected.value) {
        console.log('SignalR连接超时，使用模拟数据');
        this.provideMockData();
      }
    }, 5000);

    this.hubConnection
      .start()
      .then(() => {
        console.log('SignalR连接成功');
        this.isConnected.next(true);
        this.registerSignalREvents();
        this.subscribeToStockUpdates();
      })
      .catch(err => {
        console.error('SignalR连接失败: ', err);
        this.isConnected.next(false);
        
        this.provideMockData();
        
        setTimeout(() => this.startConnection(), 30000);
      });

    this.hubConnection.onclose(() => {
      console.log('SignalR连接已关闭');
      this.isConnected.next(false);
      
      this.provideMockData();
      
      setTimeout(() => this.startConnection(), 10000);
    });
  }

  /**
   * 提供模拟数据
   */
  private provideMockData(forceUpdate: boolean = false): void {
    if (this.dashboardData.value && !forceUpdate) {
      return;
    }
    
    console.log('提供模拟的库存仪表盘数据');
    
    const now = new Date();
    const variance = this.lastMockDataTime ? 
      Math.floor((now.getTime() - this.lastMockDataTime.getTime()) / 1000) : 0;
    
    this.lastMockDataTime = now;
    
    const fluctuation = Math.floor(Math.random() * 100) + variance;
    const totalStock = 1070 + fluctuation;
    const totalAmount = 10300 + fluctuation * 10;
    
    const warehouseStock1 = Math.floor(totalStock * (0.5 + Math.random() * 0.1));
    const warehouseStock2 = Math.floor(totalStock * (0.2 + Math.random() * 0.1));
    const warehouseStock3 = totalStock - warehouseStock1 - warehouseStock2;
    
    const mockData = {
      totalStock: totalStock,
      totalAmount: totalAmount.toFixed(2),
      updateTime: now.toISOString(),
      stockByWarehouse: [
        { warehouseName: '主仓库', stockCount: warehouseStock1 },
        { warehouseName: '电子仓库', stockCount: warehouseStock2 },
        { warehouseName: '食品仓库', stockCount: warehouseStock3 }
      ],
      stockByType: [
        { goodsType: '电子产品', stockCount: Math.floor(totalStock * 0.4) },
        { goodsType: '办公用品', stockCount: Math.floor(totalStock * 0.3) },
        { goodsType: '食品饮料', stockCount: Math.floor(totalStock * 0.3) }
      ],
      lowStockItems: [
        { 
          goodsCode: 'GD001', 
          goodsName: '笔记本电脑', 
          specification: '15.6英寸/i7/8G',
          unit: '台',
          warehouseName: '电子仓库',
          currentStock: Math.max(1, 5 + Math.floor(Math.random() * 3) - 1)
        },
        { 
          goodsCode: 'GD002', 
          goodsName: '矿泉水', 
          specification: '500ml',
          unit: '箱',
          warehouseName: '食品仓库',
          currentStock: Math.max(1, 8 + Math.floor(Math.random() * 3) - 1)
        }
      ]
    };
    
    this.dashboardData.next(mockData);
  }

  /**
   * 强制刷新模拟数据
   */
  public refreshMockData(): void {
    this.provideMockData(true);
  }

  /**
   * 注册SignalR事件监听器
   */
  private registerSignalREvents(): void {
    this.hubConnection.on('ReceiveStockMainUpdate', (data: any) => {
      console.log('收到库存数据更新:', data);
      this.dashboardData.next(data);
    });

    this.hubConnection.on('SubscriptionStatus', (success: boolean, message: string) => {
      console.log('订阅状态:', success, message);
      if (!success) {
        const notification = this.injector.get(NzNotificationService);
        notification.info('订阅通知', message);
      }
    });
  }

  /**
   * 订阅库存更新
   */
  public subscribeToStockUpdates(): void {
    if (this.isConnected.value) {
      this.hubConnection.invoke('SubscribeToStockUpdates')
        .catch(err => {
          console.error('订阅库存更新失败:', err);
          this.provideMockData();
        });
    } else {
      this.provideMockData();
    }
  }

  /**
   * 请求初始库存数据
   */
  public requestStockMainData(): void {
    if (this.isConnected.value) {
      this.hubConnection.invoke('RequestStockMainData')
        .catch(err => {
          console.error('请求库存数据失败:', err);
          this.provideMockData(true);
        });
    } else {
      this.provideMockData(true);
    }
  }

  /**
   * 取消订阅库存更新
   */
  public unsubscribeFromStockUpdates(): void {
    if (this.isConnected.value) {
      this.hubConnection.invoke('UnsubscribeFromStockUpdates')
        .catch(err => console.error('取消订阅库存更新失败:', err));
    }
  }

  /**
   * 关闭连接
   */
  public stopConnection(): void {
    if (this.hubConnection) {
      this.unsubscribeFromStockUpdates();
      this.hubConnection.stop()
        .then(() => {
          console.log('SignalR连接已停止');
          this.isConnected.next(false);
        })
        .catch(err => console.error('停止SignalR连接失败:', err));
    }
  }
}